package com.iyao_app.mvp.home;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.AlphaAnimation;
import com.amap.api.maps.model.animation.AnimationSet;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.iyao_app.R;
import com.iyao_app.base.BaseActivity;
import com.iyao_app.entry.HomeData;
import com.iyao_app.entry.Manor;
import com.iyao_app.entry.PageInfo;
import com.iyao_app.entry.Persons;
import com.iyao_app.entry.Pois;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.SceneData;
import com.iyao_app.entry.UpdateUser;
import com.iyao_app.entry.User;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.im.activity.AttentionActivity;
import com.iyao_app.im.activity.DiscoverActivity;
import com.iyao_app.im.activity.IMMessageListActivity;
import com.iyao_app.im.nimsdk.NimRecentContactSDK;
import com.iyao_app.manager.MessageManager;
import com.iyao_app.manager.MessageVo;
import com.iyao_app.mvp.dialog.DialogSceneActivity;
import com.iyao_app.mvp.info.PersonInfoActivity;
import com.iyao_app.mvp.other.OtherHomeActivity;
import com.iyao_app.mvp.search.SearchActivity;
import com.iyao_app.mvp.sign.SignActivity;
import com.iyao_app.mvp.storywall.StoryWallActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.CustomDialog_;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.DistanceUtil;
import com.iyao_app.util.MarkUtil;
import com.iyao_app.util.MessageEvent;
import com.iyao_app.util.ResourcesUtils;
import com.iyao_app.util.ToastUtil;
import com.iyao_app.view.NoDoubleClickListener;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.PopupWindowUtils;
import com.iyaowoqu.base_library.util.SPUtils;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.reactivestreams.Publisher;

import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 简介 ：
 * 作者 ： Administrator
 * 时间 ：2017/11/7.
 */

public class MainActivity extends BaseActivity implements MainContract.View, AMapLocationListener {


    @BindView(R.id.mapView)
    MapView mMapView;
    //    @BindView(R.id.sdv_head)
//    SimpleDraweeView mSdvHead;
    MainContract.Presenter mPresenter;
    @BindView(R.id.iv_head_king)
    ImageView mIvHeadKing;
    @BindView(R.id.tv_location)
    TextView mTvLocation;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.iv_next)
    ImageView mIvNext;
    @BindView(R.id.rl_head)
    RelativeLayout mRlHead;
    @BindView(R.id.iv_person)
    ImageView mIvPerson;
    @BindView(R.id.iv_field)
    ImageView mIvField;
    @BindView(R.id.tv_all_man)
    TextView mTvAllMan;
    @BindView(R.id.tv_only_man)
    TextView mTvOnlyMan;
    @BindView(R.id.tv_only_woman)
    TextView mTvOnlyWoman;
    @BindView(R.id.lin_person)
    LinearLayout mLinPerson;
    @BindView(R.id.lin_message)
    RecyclerView mLinMessage;
    @BindView(R.id.rl_root)
    RelativeLayout rl_root;
    @BindView(R.id.iv_refresh)
    ImageView mIvRefresh;
    @BindView(R.id.v_message)
    View mVMessage;

    AMap aMap;
    final int MODE_PERSON = 0;
    final int MODE_FIELD = 1;
    int mode = MODE_PERSON;
    final int PERSON_ALL = 0;
    final int PERSON_MAN = 1;
    final int PERSON_WOMAN = 2;
    int person_mode = PERSON_ALL;
    private Circle circle;
    private final int REQUEST_CODE_LOCATION = 100;
    private final int REQUEST_CODE = 0;
    private final int pageSize = 10;
    private boolean isRefreshPerson = false;
    private int page = 1;
    private PageInfo pageInfo;

    private PageInfo pageInfoRound;
    private int pageRound = 1;
    private boolean isRefreshRound = false;

    boolean haveLocationPermission = true;

    private List<Persons> persons;
    private LatLng currentLng = null;
    private LatLng selectLng = null;

    private List<Pois> pois;
    private Animation rotate;
    private BitmapDescriptor myDescrip;
    private String city;
    private Manor manor;
    private boolean sceneChange = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().post(this);
        }
        int unreadNum = NIMClient.getService(MsgService.class).getTotalUnreadCount();
        LogUtil.e("a", "weidu" + unreadNum);
        Drawable drawable = getResources().getDrawable(R.color.app_black_bg);
        this.getWindow().setBackgroundDrawable(drawable);
        setContentView(R.layout.activity_main);
        new MainPresenter(this);
        ButterKnife.bind(this);
        init(savedInstanceState);
        updateMultiportPushConfig();
//        MessageBoxSdk.observeMsgStatus();
        updateTotalUnReadCount();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updaManor(MessageEvent event) {
        LogUtil.e("==mainactivityupdaManor===");
        if (event.getState() == MessageEvent.MANOR) {
            LogUtil.e("==updaManor===");
            getManor();
        }
    }

    private void init(Bundle savedInstanceState) {
        initMap(savedInstanceState);
        changePersonMode(person_mode);
        changeMode(mode);
        loginYun();
        mIvRefresh.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                hidePerson();
                if (sceneChange) {
                    new CustomDialog_(MainActivity.this)
                            .setConfirmText(ResourcesUtils.getString(R.string.confirm_))
                            .setContent(ResourcesUtils.getString(R.string.change_linzhu))
                            .setCanceled(false)
                            .setOnConfirmClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    sceneChange = false;
                                    updateRefresh();
                                    getManor();
                                }
                            })
                            .setOnCancelClickListener(null)
                            .show();
                } else {
                    updateRefresh();
                    if (manor == null) {
                        getManor();
                    }
                }
            }
        });
        mRlHead.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                hidePerson();
                if (manor != null) {
                    Intent intent = new Intent(MainActivity.this, DialogSceneActivity.class);
                    manor.type = 1;
                    intent.putExtra(Contants.THIRD_FIELD, manor);
                    startActivityForResult(intent, REQUEST_CODE);
                    overridePendingTransition(R.anim.dialog_activity_enter, 0);
                }
            }
        });
    }

    /**
     * 更新最近联系人中消息未读总数
     */
    private void updateTotalUnReadCount() {
        int totalUnreadCount = NimRecentContactSDK.getTotalUnreadCount();
        LogUtil.e("aabbcc", totalUnreadCount + "");
//        if (activity.mTvMessageCount != null)
//            if (totalUnreadCount > 0) {
//                activity.mTvMessageCount.setVisibility(View.VISIBLE);
//                activity.mTvMessageCount.setText(String.valueOf(totalUnreadCount > 99 ? 99 : totalUnreadCount));
//            } else {
//                activity.mTvMessageCount.setVisibility(View.GONE);
//            }
    }

    @PermissionYes(REQUEST_CODE_LOCATION)
    private void getMultiYes(@NonNull List<String> grantedPermissions) {
        LogUtil.e("成功");
        haveLocationPermission = true;
        if (currentLng != null) {
            setLocationChange(currentLng);
        } else {
            location();
        }
        initMessageLooper();

        boolean homeFirst = SPUtils.getInstance().getBoolean(Contants.HOME_FIRST, true);
        if (homeFirst) {
            if (MainActivity.this != null && !MainActivity.this.isFinishing()) {
                fistEnter();
            }
        }
    }


    @PermissionNo(REQUEST_CODE_LOCATION)
    private void getMultiNo(@NonNull List<String> deniedPermissions) {
        haveLocationPermission = false;
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            AndPermission.defaultSettingDialog(this, 100)
                    .setTitle("权限申请失败")
                    .setMessage("定位权限被拒绝或者系统发生错误申请失败,请您到设置页面手动授权，否则功能无法正常使用！")
                    .setPositiveButton("好，去设置")
                    .setNegativeButton("拒绝", null)
                    .show();

        }
    }

    private void initMap(Bundle savedInstanceState) {
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        blackMap();
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(false);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.getUiSettings().setZoomControlsEnabled(false);
//        aMap.getUiSettings().setAllGesturesEnabled(false);
        aMap.getUiSettings().setRotateGesturesEnabled(false);

        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                LogUtil.e("===" + Thread.currentThread().getName());

                AndPermission.with(MainActivity.this)
                        .requestCode(REQUEST_CODE_LOCATION)
                        .permission(Permission.LOCATION)
                        .rationale(new RationaleListener() {
                            @Override
                            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                AndPermission.rationaleDialog(MainActivity.this, rationale).show();
                            }
                        })
                        .callback(MainActivity.this)
                        .start();
            }
        });

        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                hidePerson();

            }
        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                hidePerson();
                Intent intent;
                String id = marker.getTitle();
                LogUtil.e("===id==" + id);
                LatLng position = marker.getPosition();
                if (mode == MODE_PERSON) {
                    if (!"我的位置".equals(id)) {
                        intent = new Intent(MainActivity.this, OtherHomeActivity.class);
                        intent.putExtra(Contants.TYPE, String.valueOf(id));
                        startActivity(intent);
                    }
                } else {
                    manor.type = 1;
                    manor.sceneId = id;
                    manor.longitude = position.longitude;
                    manor.latitude = position.latitude;
                    intent = new Intent(MainActivity.this, DialogSceneActivity.class);
                    intent.putExtra(Contants.THIRD_FIELD, manor);
                    startActivityForResult(intent, REQUEST_CODE);
                    overridePendingTransition(R.anim.dialog_activity_enter, 0);
                }
                return true;
            }
        });

    }


    private void blackMap() {
        try {
            //开启自定义样式
            aMap.setMapCustomEnable(true);
            //加载个性化的地图底图数据
            aMap.setCustomMapStylePath(Environment.getExternalStorageDirectory()
                    + File.separator + "style/mystyle_sdk_1511952973_0100.data");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void fistEnter() {

        final PopupWindowUtils popupWindowUtils = PopupWindowUtils.getInstance();
        popupWindowUtils.attachActivity(MainActivity.this, R.layout.home_guide, rl_root)
                .wiewSize(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
                .location(Gravity.CENTER)
                .isDarkened(false)
                .Animation(PopupWindowUtils.ANIMATION_DIALOG)
                .setPopupWindowItemViewClickListener(new PopupWindowUtils.SetonPopWindowItemViewClickListenter() {
                    @Override
                    public void onPopWindowItemViewClickListener(int id) {
                        popupWindowUtils.dissMissPopWindow();
                        SPUtils.getInstance().put(Contants.HOME_FIRST, false);
                    }
                }, R.id.v_pop)
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        for (Marker marker : aMap.getMapScreenMarkers()) {

            marker.remove();
        }
        mMapView.onDestroy();
        if (mLocationClient != null)
            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
        blackMap();
        if (!haveLocationPermission)
            // Activity:
            AndPermission.with(this)
                    .requestCode(REQUEST_CODE_LOCATION)
                    .permission(Permission.LOCATION)
                    .rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                            AndPermission.rationaleDialog(MainActivity.this, rationale).show();
                        }
                    })
                    .callback(this)
                    .start();
        int unreadNum = NIMClient.getService(MsgService.class).getTotalUnreadCount();
        if (unreadNum == 0) {
            mVMessage.setVisibility(View.GONE);
        } else {
            mVMessage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        blackMap();
        if (currentLng != null) {

        }
        mLocationClient.startLocation();
        upDateUser();
    }

    private void upDateUser() {
        if (DbUtil.getUser() != null && !TextUtils.isEmpty(DbUtil.getUser().id)) {
            NetUtils.getInstance().userInfo(DbUtil.getUser().id, new NetCallBack() {
                @Override
                public void onSuccess(String message, int code, String response, ResultModel model) {
                    if (code == Contants.SUCCESS_CODE) {
                        if (model != null) {
                            UpdateUser updateUser = model.getModel();
                            User user = DbUtil.getUser();
                            user.id = updateUser.id;
                            user.token = updateUser.token;
                            user.nickname = updateUser.nickname;
                            user.sex = updateUser.sex;
                            user.avatarUrl = updateUser.avatarUrl;
                            DbUtil.updateUserInfo(user);
                            loginYun();
                        }
                    }
                }

                @Override
                public void onFail(String message, int code) {

                }
            }, UpdateUser.class);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    /**
     * 双击退出函数
     **/
    private static Boolean isExit = false;

    public void exitBy2Click() {
        Timer tExit;
        if (!isExit) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); //如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            //false，仅当activity为task根（即首个activity例如启动activity之类的）时才生效
            //true，无论什么时候都会生效，忽略上述条件
            moveTaskToBack(true);
//            MyApplication.getInstance().exitApp();
        }
    }


    @Override
    public void updateMap() {

    }

    @Override
    public void showLinZhu(Manor manor) {
        if (manor != null) {
            mRlHead.setVisibility(View.VISIBLE);
//            mTvLocation.setText(persons.longitude);

//            if (TextUtils.isEmpty(manor.avatarUrl)) {
//                mIvHeadKing.setVisibility(View.INVISIBLE);
//                mSdvHead.setImageResource(MarkUtil.getId(manor.typecode));
//            } else {
//                mIvHeadKing.setVisibility(View.VISIBLE);
//                Uri uri = Uri.parse(manor.avatarUrl);
//                ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
//                        .setResizeOptions(new ResizeOptions(100, 100))
//                        .build();
//                PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
//                        .setOldController(mSdvHead.getController())
//                        .setImageRequest(request)
//                        .build();
//                mSdvHead.setController(controller);
//            }
            if (TextUtils.isEmpty(manor.name)) {
                mTvLocation.setText(manor.address);
            } else {
                mTvLocation.setText(manor.name);
            }

//            if (TextUtils.isEmpty(manor.nickName)) {
//                mTvName.setText(R.string.no_lin_zhu);
//            } else {
//                mTvName.setText("领主: " + manor.nickName);
//            }

        }
    }

    @Override
    public void setPresenter(MainContract.Presenter presenter) {
        mPresenter = presenter;
        mPresenter.start();
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hidProgress() {

    }

    @OnClick({R.id.tv_all_man, R.id.tv_only_man, R.id.tv_only_woman, R.id.iv_tab_0, R.id.iv_tab_1, R.id.iv_tab_2, R.id.iv_tab_3, R.id.iv_tab_4, R.id.tv_name, R.id.iv_next, R.id.iv_person, R.id.iv_field, R.id.iv_search, R.id.iv_message, R.id.iv_shop})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {


            case R.id.tv_name:
                hidePerson();
//                if (!TextUtils.isEmpty(manor.userId)) {
//                    intent = new Intent(MainActivity.this, OtherHomeActivity.class);
//                    intent.putExtra(Contants.TYPE, manor.userId);
//                    startActivity(intent);
//                }
                break;
            case R.id.iv_next:
                hidePerson();
                break;
            case R.id.iv_person:
                if (currentLng == null) return;
                if (sceneChange && manor.type != 1) {
                    new CustomDialog_(this)
                            .setConfirmText(ResourcesUtils.getString(R.string.confirm_))
                            .setContent(ResourcesUtils.getString(R.string.change_linzhu))
                            .setCanceled(false)
                            .setOnConfirmClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    sceneChange = false;
                                    updatePerson();
                                    getManor();
                                }
                            })
                            .setOnCancelClickListener(null)
                            .show();
                } else {
                    updatePerson();
                }
                break;
            case R.id.iv_field:
                hidePerson();
                if (currentLng == null) return;

                if (sceneChange && manor.type != 1) {
                    new CustomDialog_(this)
                            .setConfirmText(ResourcesUtils.getString(R.string.confirm_))
                            .setContent(ResourcesUtils.getString(R.string.change_linzhu))
                            .setCanceled(false)
                            .setOnConfirmClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    sceneChange = false;
                                    updateSene();
                                    getManor();
                                }
                            })
                            .setOnCancelClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mode = MODE_FIELD;
                                    changeMode(mode);
                                    requestRound(1);
                                }
                            })
                            .show();
                } else {
                    updateSene();
                }
                break;

            case R.id.iv_search:
                hidePerson();
                if (selectLng != null) {
                    intent = new Intent(MainActivity.this, SearchActivity.class);
                    if (manor == null) {
                        manor = new Manor();
                        manor.latitude = currentLng.latitude;
                        manor.longitude = currentLng.longitude;
                    }
                    intent.putExtra(Contants.THIRD_FIELD, manor);
//                    intent.putExtra(Contants.TYPE, currentLng);
                    intent.putExtra(Contants.OTHER_FIELD, city);
                    intent.putExtra(Contants.CLASS_TYPE, 0);
                    startActivityForResult(intent, REQUEST_CODE);
                } else {
                    mLocationClient.startLocation();
                }
                break;
            case R.id.iv_message:
                hidePerson();
                int unreadNum = NIMClient.getService(MsgService.class).getTotalUnreadCount();
                if (unreadNum == 0) {
                    mVMessage.setVisibility(View.GONE);
                } else {
                    mVMessage.setVisibility(View.VISIBLE);
                }
//                startActivity(new Intent(this, MessageListActivity.class));
                startActivity(new Intent(this, IMMessageListActivity.class));
                break;
            case R.id.iv_shop:
                hidePerson();
//                MessageVo vo = new MessageVo();
//                vo.setName("迪丽热巴");
//                vo.setTime("1小时前");
//                vo.setLocation("北京市回龙观sdaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
//                vo.setImage(ImageData.s1);
//                addMessage(vo);

                startActivity(new Intent(this, PersonInfoActivity.class));
                break;
            case R.id.tv_all_man:
                if (currentLng == null) return;
                person_mode = PERSON_ALL;
                changePersonMode(person_mode);
                isRefreshPerson = false;
                requestPerson();
                break;
            case R.id.tv_only_man:
                if (currentLng == null) return;
                person_mode = PERSON_MAN;
                changePersonMode(person_mode);
                isRefreshPerson = false;
                requestPerson();
                break;
            case R.id.tv_only_woman:
                if (currentLng == null) return;
                person_mode = PERSON_WOMAN;
                changePersonMode(person_mode);
                isRefreshPerson = false;
                requestPerson();
                break;
            case R.id.iv_tab_0:
                if (manor == null) return;
                intent = new Intent(this, StoryWallActivity.
                        class);
                intent.putExtra(Contants.THIRD_FIELD, manor);
                intent.putExtra(Contants.TYPE, currentLng);
                startActivity(intent);
                break;
            case R.id.iv_tab_1:
                startActivity(new Intent(this, DiscoverActivity.class));
                break;
            case R.id.iv_tab_2:
                if (selectLng != null) {
                    double distance = DistanceUtil.getDistance_(currentLng, selectLng);
                    LogUtil.e("==distance==" + distance);
                    if (distance > 500) {
                        Toast.makeText(this, "您的位置距离该场景超出500米无法签到", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (manor == null) return;
                intent = new Intent(this, SignActivity.class);
                manor.latitude = currentLng.latitude;
                manor.longitude = currentLng.longitude;
                intent.putExtra(Contants.THIRD_FIELD, manor);
                intent.putExtra(Contants.OTHER_FIELD, city);
                startActivity(intent);
                break;
            case R.id.iv_tab_3:
                intent = new Intent(this, AttentionActivity.class);
                intent.putExtra(Contants.TYPE, 0);
                startActivity(intent);
                break;
            case R.id.iv_tab_4:
                startActivity(new Intent(this, PersonInfoActivity.class));
                break;

        }
    }

    private void updateRefresh() {
        if (currentLng == null) {
            mLocationClient.startLocation();
            return;
        }

        if (mode == MODE_FIELD) {
            isRefreshRound = true;
            requestRound(0);
        } else {
            isRefreshPerson = true;
            requestPerson();
        }
        if (currentLng != null) {
            CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(currentLng, Contants.ZOOM, 0, 0));
            //AMap类中提供，带有移动过程的动画
            aMap.animateCamera(cameraUpdate, 500, null);
        }
    }

    private void updateSene() {
        mode = MODE_FIELD;
        changeMode(mode);
        isRefreshRound = false;
        requestRound(0);
    }

    private void updatePerson() {
        if (mode == MODE_PERSON) {//展开
            if (mLinPerson.getVisibility() == View.VISIBLE) {
                mLinPerson.setVisibility(View.GONE);
            } else {
                mLinPerson.setVisibility(View.VISIBLE);
                ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 1, 1, 0, 0.5f);
                scaleAnimation.setDuration(500);
                mLinPerson.setAnimation(scaleAnimation);
            }
        } else {//切换回人物模式
            mode = MODE_PERSON;
            changeMode(mode);
            isRefreshPerson = false;
            requestPerson();
        }
    }

    private void addMessage(final MessageVo messageVo) {
        Glide.with(this).load(messageVo.getImage()).asBitmap().override(100, 100).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                messageVo.setBitmap(resource);
                messageManager.addMessage(messageVo);
            }
        });
    }

    private MessageManager messageManager = null;

    private void initMessageLooper() {
        if (messageManager == null) {
            messageManager = new MessageManager(this, mLinMessage);
        }
    }


    private void hidePerson() {
        if (mLinPerson.getVisibility() == View.VISIBLE) {
            mLinPerson.setVisibility(View.GONE);
        }
    }

    private void changeMode(int mode) {
        switch (mode) {
            case MODE_PERSON:
                mIvPerson.setSelected(true);
                mIvField.setSelected(false);
                break;
            case MODE_FIELD:
                mIvPerson.setSelected(false);
                mIvField.setSelected(true);
                break;
        }

    }

    private void changePersonMode(int mode) {
        switch (mode) {
            case PERSON_ALL:
                mTvAllMan.setSelected(true);
                mTvOnlyMan.setSelected(false);
                mTvOnlyWoman.setSelected(false);
                break;
            case PERSON_MAN:
                mTvAllMan.setSelected(false);
                mTvOnlyMan.setSelected(true);
                mTvOnlyWoman.setSelected(false);
                break;
            case PERSON_WOMAN:
                mTvAllMan.setSelected(false);
                mTvOnlyMan.setSelected(false);
                mTvOnlyWoman.setSelected(true);
                break;
        }

    }


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;


    private void location() {

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);


        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);


        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);

        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(false);

        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        //初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
//        myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);//连续定位、且将视角移动到地图中心点，定位蓝点跟随设备移动。（1秒1次定位）
//        //        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE);//连续定位、且将视角移动到地图中心点，地图依照设备方向旋转，定位点会跟随设备移动。（1秒1次定位）
//        //        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）默认执行此种模式。
//        myLocationStyle.strokeColor(Color.TRANSPARENT);
//        myLocationStyle.radiusFillColor(Color.TRANSPARENT);
//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_my_location));
//        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style

        //启动定位
        mLocationClient.startLocation();
    }

    private void markScren(Pois o) {
//        final View coverView = LayoutInflater.from(MainActivity.this).inflate(R.layout.cover_item, null);

        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(MarkUtil.getId_(o.getTypecode()));
        MarkerOptions markerOption = new MarkerOptions();
        String location = o.getLocation();
        String[] split = location.split(",");
        markerOption.position(new LatLng(Double.parseDouble(split[1]), Double.parseDouble(split[0])));
        markerOption.draggable(false);//设置Marker可拖动
        markerOption.icon(bitmapDescriptor);
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(false);//设置marker平贴地图效果
        markerOption.anchor(0.5f, 1.0f);

        AnimationSet animationSet = new AnimationSet(true);
        com.amap.api.maps.model.animation.ScaleAnimation scaleAnimation = new com.amap.api.maps.model.animation.ScaleAnimation(0, 1, 0, 1);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
        animationSet.addAnimation(alphaAnimation);
        animationSet.addAnimation(scaleAnimation);
        long duration = 1000L;
        animationSet.setDuration(duration);
        animationSet.setInterpolator(new BounceInterpolator());
        Marker marker = aMap.addMarker(markerOption);
        marker.setAnimation(animationSet);
        marker.setTitle(o.getSceneId());
        marker.startAnimation();
    }

    private void downLoadImg(final Persons o) {

        Glide.with(this).load(o.avatarUrl).asBitmap().override(100, 100).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                View coverView = LayoutInflater.from(MainActivity.this).inflate(R.layout.cover_item, null);
                CircleImageView coverHead = coverView.findViewById(R.id.cover_head);
                //bitmap即为下载所得图片
                LogUtil.e("==bitmap===");
                coverHead.setImageBitmap(resource);
                BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromView(coverView);
                MarkerOptions markerOption = new MarkerOptions();
                markerOption.position(new LatLng(o.latitude, o.longitude));
                markerOption.draggable(false);//设置Marker可拖动
                markerOption.icon(bitmapDescriptor);
                // 将Marker设置为贴地显示，可以双指下拉地图查看效果
                markerOption.setFlat(false);//设置marker平贴地图效果
                markerOption.anchor(0.5f, 1.0f);

                AnimationSet animationSet = new AnimationSet(true);
                com.amap.api.maps.model.animation.ScaleAnimation scaleAnimation = new com.amap.api.maps.model.animation.ScaleAnimation(0, 1, 0, 1);
                AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
                animationSet.addAnimation(alphaAnimation);
                animationSet.addAnimation(scaleAnimation);
                long duration = 1000L;
                animationSet.setDuration(duration);
                animationSet.setInterpolator(new BounceInterpolator());
                Marker marker = aMap.addMarker(markerOption);
                marker.setAnimation(animationSet);
                marker.setTitle(o.userId);
                marker.startAnimation();
                resource.recycle();

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mLocationClient != null)
            mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
    }

    private void drawCircle(LatLng latLng) {
        if (circle != null) {
            circle.remove();
        }
        circle = aMap.addCircle(new CircleOptions().
                center(latLng).
                radius(Contants.RADIUS).
                fillColor(ResourcesUtils.getColor(R.color.white_alpha)).
                strokeColor(ResourcesUtils.getColor(R.color.white_alpha)).
                strokeWidth(0));
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation == null || aMapLocation.getErrorCode() != 0) {
            //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
            LogUtil.e("定位失败");
            ToastUtil.showToast(this, "获取当前位置信息失败!");
            return;
        }
        if (aMapLocation.getErrorCode() == 0) {
            if (currentLng == null) {
                currentLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                if (selectLng == null)
                    selectLng = currentLng;
                city = aMapLocation.getCity();
                LogUtil.e("=city==" + city);
                setLocationChange(currentLng);
            } else {
                if (currentLng.latitude == aMapLocation.getLatitude() && currentLng.longitude == aMapLocation.getLongitude()) {//坐标一样
                    LogUtil.e("定位坐标一样");
                } else {
                    currentLng = null;

                    currentLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                    setLocationChange(currentLng);
                }
            }
        }
    }

    private void requestRound(final int tp) {
        if (currentLng == null)
            return;
        if (isRefreshRound) {
            if (pageInfoRound != null) {
                if (pageInfoRound.pageTotal > pageRound) {
                    pageRound++;
                } else {
                    pageRound = 1;
                }
            }
        } else {
            pageRound = 1;
        }
//        if (isRefreshRound)
//            startRefreshAnimtion();
        NetUtils.getInstance().round(currentLng.longitude, currentLng.latitude, Contants.RADIUS, pageSize, pageRound, new NetCallBack() {
            @Override
            public void onSuccess(String message, final int code, String response, final ResultModel model) {

                if (code == Contants.SUCCESS_CODE) {
//                    if (isRefreshRound)
//                        stopRefreshAnimtion();
                    if (model != null) {
                        HomeData homeData = model.getModel();
                        if (homeData != null) {
                            pageInfoRound = null;
                            pois = null;
                        }
                        pageInfoRound = homeData.getPageInfo();
                        pois = homeData.getPois();
                        resolveField(tp);
                    }
                }
            }

            @Override
            public void onFail(String message, int code) {
                if (isRefreshRound)
                    stopRefreshAnimtion();
            }
        }, HomeData.class);
    }

    private void requestPerson() {
        if (currentLng == null)
            return;
        if (isRefreshPerson) {
            if (pageInfo != null) {
                if (pageInfo.pageTotal > page) {
                    page++;
                } else {
                    page = 1;
                }
            }
        } else {
            page = 1;
        }
        if (isRefreshPerson)
            startRefreshAnimtion();
        NetUtils.getInstance().nearByPerson(currentLng.longitude, currentLng.latitude, Contants.RADIUS, pageSize, page, person_mode, new NetCallBack() {
            @Override
            public void onSuccess(String message, final int code, String response, final ResultModel model) {

                if (isRefreshPerson)
                    stopRefreshAnimtion();
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {
                        HomeData homeData = model.getModel();
                        if (homeData != null) {
                            pageInfo = null;
                            persons = null;
                        }
                        pageInfo = homeData.getPageInfo();
                        persons = homeData.getPersons();
                        resolvePerson();
                    }
                }
            }

            @Override
            public void onFail(String message, int code) {

                if (isRefreshPerson)
                    stopRefreshAnimtion();
            }
        }, HomeData.class);
    }

    private void startRefreshAnimtion() {
        mIvRefresh.setImageResource(R.mipmap.btn_huanyipi);
        if (rotate == null) {
            rotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_anim);
            LinearInterpolator lir = new LinearInterpolator();
            rotate.setInterpolator(lir);
        }
        mIvRefresh.startAnimation(rotate);

    }

    private void stopRefreshAnimtion() {
        Observable.timer(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {

                    @Override
                    public void accept(Long aLong) throws Exception {
                        mIvRefresh.clearAnimation();
                        mIvRefresh.setImageResource(R.mipmap.ic_huanyipi);
                    }
                });

    }

    private void resolveField(int tp) {
        mode = MODE_FIELD;
        aMap.clear();
        if (tp == 1) {
            maker(manor);
        }
        drawMyLocation(currentLng, tp);
        if (pois == null || pois.size() == 0)
            return;
        Flowable.fromArray(pois).concatMap(new Function<List<Pois>, Publisher<Pois>>() {

            @Override
            public Publisher<Pois> apply(List<Pois> makerInfos) throws Exception {
                return Flowable.fromIterable(pois);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Pois>() {
                    @Override
                    public void accept(Pois o) throws Exception {
                        markScren(o);
                    }
                });
    }

    private void resolvePerson() {
        mode = MODE_PERSON;
        aMap.clear();
        drawMyLocation(currentLng, 0);
        if (persons == null || persons.size() == 0)
            return;
        Observable.fromArray(persons).concatMap(new Function<List<Persons>, ObservableSource<Persons>>() {
            @Override
            public ObservableSource<Persons> apply(List<Persons> persons) throws Exception {

                return Observable.fromIterable(persons);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Persons>() {
                    @Override
                    public void accept(Persons o) throws Exception {
                        downLoadImg(o);
                    }
                });
    }

    private void setLocationChange(LatLng latLng) {
        //清除所有maker
        for (int i = 0; i < aMap.getMapScreenMarkers().size(); i++) {
            Marker marker = aMap.getMapScreenMarkers().get(i);
            marker.remove();
        }
        requestPerson();
        getManor();
    }

    private void getManor() {
        if (currentLng == null)
            return;
        NetUtils.getInstance().manor(currentLng.longitude, currentLng.latitude, Contants.RADIUS, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model == null) return;
                    manor = model.getModel();
                    showLinZhu(manor);
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, Manor.class);
    }

    private void drawMyLocation(final LatLng latLng, int tp) {
        if (tp == 1) {
            markMy(latLng);
        } else {
            markMy(latLng);
            //参数依次是：视角调整区域的中心点坐标、希望调整到的缩放级别、俯仰角0°~45°（垂直与地图时为0）、偏航角 0~360° (正北方为0)
            CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, Contants.ZOOM, 0, 0));
            //AMap类中提供，带有移动过程的动画
            aMap.animateCamera(mCameraUpdate, 500, new AMap.CancelableCallback() {
                @Override
                public void onFinish() {

                }

                @Override
                public void onCancel() {

                }
            });
        }
    }

    private void markMy(LatLng latLng) {
        if (myDescrip == null) {
            myDescrip = BitmapDescriptorFactory.fromResource(R.mipmap.ic_my_location);
        }
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.draggable(false);//设置Marker可拖动
        markerOption.icon(myDescrip);
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(false);//设置marker平贴地图效果
        markerOption.anchor(0.5f, 0.5f);
        Marker marker = aMap.addMarker(markerOption);
        marker.setTitle("我的位置");
        drawCircle(latLng);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e("=-==onActivityResult==");
        if (requestCode == REQUEST_CODE && resultCode == SearchActivity.RESULT_CODE) {
            LogUtil.e("=-==REQUEST_CODE !==");
            if (data != null) {
                LogUtil.e("=-==data !==");

                final Manor manor0 = (Manor) data.getSerializableExtra(Contants.TYPE);
                selectLng = new LatLng(manor0.latitude, manor0.longitude);
                sceneChange = true;
                Observable.timer(1, TimeUnit.SECONDS).subscribe(new Consumer<Long>() {

                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (selectLng != null) {
                            //参数依次是：视角调整区域的中心点坐标、希望调整到的缩放级别、俯仰角0°~45°（垂直与地图时为0）、偏航角 0~360° (正北方为0)
                            CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(selectLng, Contants.ZOOM, 0, 0));
                            //AMap类中提供，带有移动过程的动画
                            aMap.animateCamera(mCameraUpdate, 500, new AMap.CancelableCallback() {
                                @Override
                                public void onFinish() {
                                    sceneInfo(manor0);
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                        }
                    }
                });

            }
        }
    }

    private void sceneInfo(final Manor manor0) {
        NetUtils.getInstance().sceneInfo(manor0.sceneId, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {
                        SceneData sceneData = model.getModel();
                        if (sceneData != null) {
                            SceneData.ManorInfoBean manorInfo = sceneData.manorInfo;
                            if (manorInfo != null) {
                                manor.nickName = manorInfo.nickName;
                                manor.userId = manorInfo.userId;
                                manor.avatarUrl = manorInfo.avatarUrl;
                            } else {
                                manor.nickName = "";
                                manor.userId = "";
                                manor.avatarUrl = "";
                            }
                            manor.latitude = manor0.latitude;
                            manor.longitude = manor0.longitude;
                            manor.typecode = manor0.typecode;
                            manor.sceneId = manor0.sceneId;
                            if (TextUtils.isEmpty(sceneData.name)) {
                                manor.name = manor0.name;
                            } else {
                                manor.name = sceneData.name;
                            }
                            if (TextUtils.isEmpty(sceneData.address)) {
                                manor.address = manor0.address;
                            } else {
                                manor.address = sceneData.address;
                            }
                            manor.type = manor0.type;
                            showLinZhu(manor);
                            if (mode == MODE_FIELD) {
                                if (manor0.type != 1)
                                    maker(manor);
                            }
                        }
                    }
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, SceneData.class);
    }

    private void maker(Manor manor0) {
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(MarkUtil.getId_(manor0.typecode));
        MarkerOptions markerOption = new MarkerOptions();

        markerOption.position(selectLng);
        markerOption.draggable(false);//设置Marker可拖动
        markerOption.icon(bitmapDescriptor);
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(false);//设置marker平贴地图效果
        markerOption.anchor(0.5f, 1.0f);

        AnimationSet animationSet = new AnimationSet(true);
        com.amap.api.maps.model.animation.ScaleAnimation scaleAnimation = new com.amap.api.maps.model.animation.ScaleAnimation(0, 1, 0, 1);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
        animationSet.addAnimation(alphaAnimation);
        animationSet.addAnimation(scaleAnimation);
        long duration = 1000L;
        animationSet.setDuration(duration);
        animationSet.setInterpolator(new BounceInterpolator());
        Marker marker = aMap.addMarker(markerOption);
        marker.setAnimation(animationSet);
        marker.setTitle(manor0.typecode);
        marker.startAnimation();
    }


    public void updateMultiportPushConfig() {

    }
}

